package com.ygqh.baby.observer;

import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.service.YgCouponDetailService;
import com.ygqh.baby.service.YgOrderService;
import com.ygqh.baby.service.YgPromotionService;
import com.ygqh.baby.service.YgUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

/**
 * @Auther: sunshuo
 * @Date: 2018/8/29 16:43
 * @Description: 订单满返优惠券
 */
@Component
public class ManFanCouponObserver implements Observer {

	private Logger logger = Logger.getLogger(this.getClass());

	@Autowired
	private YgPromotionService ygPromotionService;
	@Autowired
	private YgOrderService ygOrderService;
	@Autowired
	private YgCouponDetailService ygCouponDetailService;
	@Autowired
	private YgUserService ygUserService;

	@Override
	public void update(Observable o, Object arg) {
		OrderPayModel model = arg != null ? (OrderPayModel) arg : null;
		if (model == null || model.getOrderId() == null) {
			logger.error(o.getClass().getName() + ": orderCode 为空");
			return;
		}
		new Thread(() -> manFanCoupon(model.getOrderId())).start();
	}

	/**
	 * 满返赠券逻辑异步处理，不影响主线程逻辑
	 * @param orderId 订单编号
	 */
	private void manFanCoupon(Long orderId) {
		Map manFanCoupon = ygPromotionService.getManFanCoupon();
		if (manFanCoupon == null || manFanCoupon.get("limitPrice") == null || manFanCoupon.get("couponBatchIds") == null) {
			return;
		}
		String limitStr = manFanCoupon.get("limitPrice").toString();
		String couponBatchIds = manFanCoupon.get("couponBatchIds").toString();
		if (StringUtils.isBlank(limitStr.trim()) || StringUtils.isBlank(couponBatchIds.trim())) {
			return;
		}
		BigDecimal limitPrice = new BigDecimal(limitStr);
		YgOrder order = ygOrderService.findByOrderId(orderId);
		if (order.getTotalPrice().compareTo(limitPrice) < 0) {
			logger.info("满返赠券: 订单不满足条件【totalPrice=" + order.getTotalPrice() + ", limitPrice=" + limitPrice + "】");
			return;
		}
		for (String couponBatchId : couponBatchIds.split(",")) {
			if (StringUtils.isNotBlank(couponBatchId.trim())) {
				ygCouponDetailService.receiveCouponWithRemark(Long.valueOf(couponBatchId),
						"订单" + order.getOrderId() + "满" + limitPrice, ygUserService.findById(order.getUserId()));
			}
		}
	}

}
